package com.duan.controller;

import com.duan.base.JSONResponse;
import com.duan.pojo.Award;
import com.duan.pojo.User;
import com.duan.service.AwardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class AwardController {
    private final AwardService awardService;

    @Autowired
    public AwardController(AwardService awardService){
        this.awardService = awardService;
    }

    //增加
    @PostMapping("/api/award/add")
    public JSONResponse add(@RequestBody Award award, HttpSession session, HttpServletResponse resp){
        User user = (User) session.getAttribute("currentUser");

        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        JSONResponse jsonResponse = new JSONResponse();
        if(user == null){
            resp.setStatus(401);// 请求要求身份验证。 对于需要登录的网页，服务器可能返回此响应。
            jsonResponse.setSuccess(false);
            jsonResponse.setCode("USR000");
            jsonResponse.setMessage("用户没有登录，不允许访问");

            return jsonResponse;
        }

        int n = awardService.add(award, user.getId());

        jsonResponse.setSuccess(true);
        jsonResponse.setData(award.getId());//useGeneratedKeys="true"起作用

        return jsonResponse;
    }

    //更新
    @PostMapping("/api/award/update")
    public JSONResponse update(@RequestBody Award award, HttpSession session, HttpServletResponse resp){
        User user = (User) session.getAttribute("currentUser");

        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        JSONResponse jsonResponse = new JSONResponse();
        if(user == null){
            resp.setStatus(401);// 请求要求身份验证。 对于需要登录的网页，服务器可能返回此响应。
            jsonResponse.setSuccess(false);
            jsonResponse.setCode("USR000");
            jsonResponse.setMessage("用户没有登录，不允许访问");

            return jsonResponse;
        }

        int n = awardService.update(award);

        jsonResponse.setSuccess(true);

        return jsonResponse;
    }

    //删除
    @GetMapping("/api/award/delete/{awardId}")
    public JSONResponse deleteAward(@PathVariable int awardId, HttpSession session, HttpServletResponse resp){
        User user = (User) session.getAttribute("currentUser");

        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        JSONResponse jsonResponse = new JSONResponse();
        if(user == null){
            resp.setStatus(401);// 请求要求身份验证。 对于需要登录的网页，服务器可能返回此响应。
            jsonResponse.setSuccess(false);
            jsonResponse.setCode("USR000");
            jsonResponse.setMessage("用户没有登录，不允许访问");

            return jsonResponse;
        }

        int n = awardService.delete(awardId);

        jsonResponse.setSuccess(true);

        return jsonResponse;
    }
}
